const jwt = require('../../Lib/Jwt')
const User = require('../../Mongoose/User')
const crypto = require('crypto')
class Auth {
    constructor() {

    }
    /**
     * 签名接口
     * 
     * @param {any} ctx 
     * @param {any} next 
     * @returns 
     * @memberof Auth
     */
    async authorize (ctx, next) {

        let user = await User.findOne({username: ctx.request.body.username})

        if (user) {
            let password = crypto.createHash('md5').update('123456').digest('hex')
            if (user.password != password) {
                ctx.throw(500, '用户密码错误')
            }
            let data = {
                id: user.id,
                username: user.username,
                avatar: user.avatar,
                avatar_img: user.avatar_img
            }

            let token = await jwt.sign(data)
            ctx.body = token

        } else {
            ctx.throw(500, '用户不存在')
        }
    }

    /**
     * 根据token获取user
     * 
     * @param {any} ctx 
     * @param {any} next 
     * @memberof Auth
     */
    async user (ctx, next) {
        ctx.body = ctx.user
    }
}
module.exports = new Auth()